<?php

namespace control;
/*
*新钢瓶库存
*/

class newSteelCylinderClass extends adIndexClass
{
    private const page = 'newSteelCylinder'; # 权限
    private const table = 'steel_cylinder'; # 数据表
    private const title = '新钢瓶库存';
    private const stateOption = ['草稿', '确认'];

    /**
     * 字段初始化
     */
    public function fieldInit(): array
    {
        $tr = [
            'code' => [
                'name'  => '出厂码',
                'width' => 200,
                'sort' => 1,
            ],
            'model'  => [
                'name'  => '规格型号',
                'width' => 200,
            ],
            'manufacturer'  => [
                'name'  => '生产厂家',
                'width' => 200,
            ],
            'leaveTime'         => [
                'name'  => '出厂日期',
                'width' => 200,
            ],
            'nextTime'         => [
                'name'  => '下次检验日期',
                'width' => 200,
            ],
            'materialId'          => [
                'name'  => '绑定物料',
                'width' => 200,
            ],
            'state'          => [
                'name'  => '状态',
                'width' => 150,
            ],

        ];
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    '出厂码'   => text(array("name" => "code")),
                    '规格型号'  => text(array("name" => "model")),
                    '单据日期' => text(["name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~']]),
                ],
                [
                    '绑定物料' => text(array("name" => "materialId")),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*销售合同入口页*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //导入
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "warehousing")) {
            $button .= "<span class='spanButton' onclick=\"layer('" . self::page . "','warehousing',$('form[name=listForm]').serialize())\">使用出库</span>\n";
        }
        if ($this->power(self::page, "delivery")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}','addMx',$('form[name=listForm]').serialize())\">绑定物料</span>\n";
        }
        if ($this->power(self::page, "confirm")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}','confirmEdit',$('form[name=listForm]').serialize())\">批量确认</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*销售合同列表*/
    public function homeSearch()
    {
        //查询结果
        $where = ' 1=1 and state != \'出库\'';
        $equal = [
            'orderNo' => $this->post('orderNo'),
            'code' => $this->post('code'),
            'model' => $this->post('model'),
            'khid' => $this->post('khid'),
            'state' => $this->post('state'),
            'coid'=>self::$coid,
            'type_cylinder'=>1
        ];
        //生成查询语句
        $where .= search([
            "=" => $equal,
        ]);

        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        $_SESSION[self::page]['where'] = $where;
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        $url = root . "control/adIndex.html?cla=" . self::page;
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = [
                "box" => ["name" => "listId", "value" => $array['id']],
            ];
            $liButton[] = $this->dominate($dominate) . hidden(["name" => "cylinderId", "value" => $array['id']]);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "leaveTime":
                        $row[] = date("Y-m-d",strtotime($array['leaveTime'] ));
                        break;
                    case "nextTime":
                        $row[] = date("Y-m-d",strtotime($array['leaveTime'] . ' +2 year'));
                        break;
                    case "materialId":
                        $row[] = "<span class='rowMoney' id='".$array['id']."'>".materialClass::getName($array['materialId'])."</span>";
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . $this->js(). clear;
        return json_encode($json, 320);
    }

    public function js()
    {
        return <<<eof
<script>
function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
        if (res.warn == 2) {
            $('#newSteelCylinderAddMx').hide()
            $('#'+res.data.listId).html(res.data.name)
        } else {
            msg(res.warn);
        }

    },'json');
}
</script>
eof;
    }

    /**
     * @return bool|string
     */
    public function addMx()
    {
        if (static::isNull($this->post('listId'))) {
            return json_encode(['warn' => '请选择钢瓶信息', 320]);
        }
        $html   =
            materialClass::typeSelect(name: 'type').
            text(array("name" => "code", "title" => "产品编码")) .
            text(array("name" => "materialName", "title" => "产品名称")) .
            text(array("name" => "model", "title" => "规格型号"));
        $button = "<input style='margin-left: 5px' onclick=\"addRow()\" type='button' class='searchSub' value='提交'>";
        $html   = $this->search($html. hidden(['name' => 'listId', 'value' => implode(',',$this->post('listId'))]));
        return $this->layer(array("title" => "选择物料", "height" => 600, "width" => 1000, "zindex" => 3, "html" => $html, "button" => $button));
    }

    /**
     *添加产品
     */
    public function addMxSearch()
    {
        $like        = [
            'name'          => $this->post('materialName'),
            'code'            => $this->post('code'),
            'model'           => $this->post('model'),
            'supplyControl' => '允许销售',
            'typePath' => $this->post('type'),
        ];
        $equal       = [
            'coid'   => self::$coid,
            'state'  => '启用',
        ];
        $where       = search(["like" => $like, "=" => $equal]);
        $page        = $this->page([
            "table"   => "material",
            "field"   => "*",
            "where"   => $where,
            'pageNum' => 50,
            "order"   => "`time` ASC",
        ]);
        $materialObj = new materialClass();
        //获取表头
        $tr[]     = ['', '分类', '产品编码', '产品名称', '规格型号'];
        //获取记录
        foreach ($page['array'] as $array) {
            $checkBox = "<input name='mxId' value='$array[id]' type='radio'>";
            $tr[]     = array(
                $checkBox,
                $materialObj::getTypePath($array['typeId']),
                $array['code'],
                $array['name'],
                $array['model']
            );
        }
        $json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr)) . hidden(['name' => 'listId', 'value' => $this->post('listId')]) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $mxId = $this->post('mxId');
        $Id = $this->post('listId');
        $listIdArr = explode(',', $Id);
        foreach ($listIdArr as $listId){
            $steel_cylinder = query('steel_cylinder',"id = '" . $listId . "'");
            if (!$this->power(self::page, 'edit')) {
                $json['warn'] = '你还没有编辑权限';
            } elseif (empty($mxId) || empty($listId)) {
                $json['warn'] = '请选择产品';
            } elseif (empty($steel_cylinder['id'])){
                $json['warn'] = '未找到钢瓶信息';
            } else {
                $json['warn'] = update(['table' => 'steel_cylinder', 'field' => ['materialId' => $mxId], 'where' => " id = '" . $listId . "'"]);
            }
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $this->logText(array("type" => self::page, "text" => "更新成功"));
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate(): bool|string
    {
        $act  = $this->post('act') ?? '';
        $pwd  = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            default:
                $act      = 'del';
                $msg      = '删除';
                $title    = '是否删除所选信息，删除后不可找回？';
                $function = 'delete';
                $form     = self::page . 'OperateForm, listForm';
                $power    = '';
                $word = true;
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 编辑安检码
     * @return bool|string
     */
    public function warehousing(): bool|string
    {
        $listId = $this->post('listId');
        if (static::isNull($listId)) {
            return json_encode(['warn' => '请选择钢瓶信息', 320]);
        }
        //数据查询
        $info = query(self::table, " id = '" . implode(',',$listId) . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must ."内部编码：" => text(["name" => "barcode", "value" => $info['barcode'] ?? null, 'class' => 'text']) . hidden(['name' => 'id', 'value' => $info['id']]),
                ]
            ]
        ]);
        //返回
        return $this->layer(["title" => "编辑钢瓶", "height" => 220, "html" => $html]);
    }

    public function warehousingEdit(): bool|string
    {
        //赋值
        $field = [
            'barcode' => $this->post('barcode') ?: '',
            'state' => '空瓶',
            'type_cylinder' => 2,
        ];
        $data = query(self::table, " id != '" . $this->post('id') . "' AND barcode = '".$field['barcode']."' AND type_cylinder=1");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (!empty($data['id'])) {
            $json['warn'] = "安检码:".$field['barcode']."重复";
        } else {
            $json['warn'] = update(["table" => self::table , "field" => $field, "where" => "id = '" . $this->post('id') . "'"]);
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $this->logText(array("type" => self::page, "text" => "更新成功"));
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = '你还没有删除的权限';
        } elseif (empty($array)) {
            $json['warn'] = '请选择钢瓶信息';
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //返回
                $warn = '删除成功';
                $x++;
                $text .= '钢瓶信息' . $warn . "。<br>";
            }
            //添加日志
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x],"成功刪除{{x}}个钢瓶信息，详情请查看日志");
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        } else {
            $title = [ '出厂码', '内部编码','规格型号', '生产厂家','出厂日期','下次检验日期', '备注'];
            $data[] = [];
            $text = $this->control['name'] . "下载了新钢瓶导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, '新钢瓶导入模板.xlsx');
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * Excel导入
     */
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑的权限';
        } else {
            $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $type_cylinder = 1;
                    $barcode = '';
                    $state = '草稿';
                    $materialId = '';
                    $lastTime = self::importDateFormat($cell['出厂日期']);
                    if ($cell['绑定物料编码']){
                        $type_cylinder = 2;
                        $state = '出库';
                        $barcode = $cell['内部编码'];
//                        $state = '确认';
                        $material = query('material',"code = '$cell[绑定物料编码]'");
                        $materialId = $material['id'];
                        $lastTime = self::importDateFormat($cell['下次检验日期']);
                    }
                    $field = array(
                        "id" => self::getId(),
                        'coid' => self::$coid,
                        'code' => $cell['出厂码'],
                        'model' => $cell['规格型号'],
                        'manufacturer' => $cell['生产厂家'],
                        'leaveTime' => self::importDateFormat($cell['出厂日期']),
                        'lastTime' => '',
                        'endTime' => '',
                        'barcode' => $barcode,
                        'materialId' => $materialId,
                        'type_cylinder' => $type_cylinder,
                        'text' => $cell['备注'],
                        'state' => $state,
                        'updateTime' => $this->time,
                        "time" => date("Y-m-d H:i:s"),
                    );

                    $annotation = [
                        'code' => '出厂码',
                        'model' => '规格型号',
                        'leaveTime' => '出厂日期',
                    ];
                    $rules = [
                        'code' => 'required',
                        'model' => 'required',
                        'leaveTime' => 'required',
                    ];
                    // 校验是否符合规则
                    $vt = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    if ($result === false) {
                        $text .= "第【{$row_list}】行：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                    }else {
                        $warn = static::insert(["table" => self::table, "field" => $field]);
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= "第【{$row_list}】行：导入成功<br>";
                        } else {
                            $text .= "第【{$row_list}】行：导入失败，编辑失败<br>";
                        }
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }

    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'出厂码',
                    'aliasName'=>'出厂码',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'内部编码',
                    'aliasName'=>'内部编码',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'生产厂家',
                    'aliasName'=>'生产厂家',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'出厂日期',
                    'aliasName'=>'出厂日期',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'下次检验日期',
                    'aliasName'=>'下次检验日期',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'绑定物料编码',
                    'aliasName'=>'绑定物料编码',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                    'isMust'=>false,
                ],
            ]
        };
    }
    /**
     * 确认
     */
    public function confirmEdit()
    {
        $listId = $this->post('listId');
        if (static::isNull($listId)) {
            return json_encode(['warn' => '请选择钢瓶信息', 320]);
        }
        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } else {
            foreach ($listId as $item){
                $json['warn'] = update(array(
                    "table" => self::table,
                    "field" => ['state'=>'确认'],
                    "where" => "id = '$item'",
                ));
            }
        }
        resp:
        return json_encode($json, 320);
    }
}